package steed.tag;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import steed.domain.application.DWZMessage;
import steed.exception.MessageExceptionInterface;
import steed.hibernatemaster.util.DaoUtil;
import steed.util.base.BaseUtil;
import steed.util.base.DevUtil;
import steed.util.base.StringUtil;

public class ExceptionMessage extends TagSupport{
	private static final long serialVersionUID = -6163891527356079693L;

	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		Exception e = (Exception)request.getAttribute("exception");
		DaoUtil.rollbackTransaction();
		if (!StringUtil.isStringEmpty(request.getHeader("X-Requested-With")) || !StringUtil.isStringEmpty(request.getParameter("ajax")) ||
				(request.getAttribute("isAjax") != null && (boolean)request.getAttribute("isAjax"))) {
			HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
			response.setHeader("Content-Type", "application/json");
			Exception obj = (Exception)request.getAttribute("exception");
			DWZMessage dwzMessage = new DWZMessage();
			dwzMessage.setStatusCode(300);
//			dwzMessage.setTitle("出错啦！");
			if(obj instanceof MessageExceptionInterface){
				dwzMessage.setMessage(((Exception)obj).getMessage());
				if(((MessageExceptionInterface)obj).getMsg() != null){
					dwzMessage.setStatusCode(((MessageExceptionInterface)obj).getMsg().getErrCode());
				}
			}else{
				if (DevUtil.devMode) {
					dwzMessage.setMessage(e.getMessage());
				}else {
					dwzMessage.setMessage("系统繁忙！");
				}
			}
			String messageJson = BaseUtil.getJson(dwzMessage);
			PrintWriter writer;
			try {
				writer = response.getWriter();
				writer.print(messageJson);
				return SKIP_PAGE;
			} catch (IOException e1) {
				BaseUtil.getLogger().debug("返回json错误信息出错!",e);
			}
			
		}
		return SKIP_BODY;
	}

}
